﻿using System.Data.Metadata.Edm;
using System.Collections.Generic;
using System.Linq;
using System;

namespace EntityGraph
{
    public static class MetadataWorkspaceExtensions
    {
        public static EntityType GetRootOrSelf(this EntityType entityType)
        {
            while (entityType != null && entityType.BaseType as EntityType != null)
            {
                entityType = entityType.BaseType as EntityType;
            }
            return entityType;
        }
        //public static IEnumerable<EntitySet> GetaAllEntitySets1(this ItemCollection itemCollection)
        //{
        //    return itemCollection..GetItems<EntitySet>().ToList();
        //}

        public static IEnumerable<EntitySet> GetAllEntitySets(this ItemCollection itemCollection)
        {
            List<EntitySet> list = new List<EntitySet>();
            EntityContainer container = itemCollection.GetItems<EntityContainer>().FirstOrDefault<EntityContainer>();
            if (container != null)
            {
                list.AddRange(container.BaseEntitySets.OfType<EntitySet>());
            }
            return list;
        }
        public static string GetTableName(this EntitySet entitySet)
        {
            MetadataProperty property;
            if (entitySet == null)
            {
                throw new ArgumentNullException("entitySet");
            }
            if (entitySet.MetadataProperties.TryGetValue("Table", false, out property))
            {
                string str = null;
                if (((property != null) && (property.Value != null)) && (((str = property.Value as string) != null) && !string.IsNullOrEmpty(str)))
                {
                    return str;
                }
            }
            return entitySet.Name;
        }
   }
}
